package com.qf.student.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {

    public EncodingFilter() {
        System.out.println("EncodingFilter.EncodingFilter");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("EncodingFilter.doFilter");
        // 1、类型转换
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 2.设置编码
        req.setCharacterEncoding("utf-8"); // 设置请求的内容的编码格式
//        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8"); // 设置响应的内容的编码

        // 3.放行
        filterChain.doFilter(req, resp);

    }

    @Override
    public void destroy() {

    }
}
